package com.siro.auth.base.security.filter;

import com.siro.auth.base.constant.CacheConstants;
import com.siro.auth.base.constant.Constants;
import com.siro.auth.base.exception.CustomerAuthenticationException;
import com.siro.auth.base.security.handler.LoginFailureHandler;
import com.siro.auth.base.security.service.UserDetailsServiceImpl;
import com.siro.auth.utils.JwtUtils;
import com.siro.auth.utils.RedisCache;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token认证过滤器 验证token有效性
 *
 * @author starsea
 * @date 2022-07-15 17:56
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //校验token
            String token = request.getHeader(Constants.TOKEN);
            if (ObjectUtils.isEmpty(token)) {
                filterChain.doFilter(request, response);
                return;
            }
            //判断redis中是否存在该token
            String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + token;
            String redisToken = redisCache.get(tokenKey);
            //如果redis里面没有token,说明该token失效
            if (ObjectUtils.isEmpty(redisToken)) {
                throw new CustomerAuthenticationException("token已过期");
            }
            //如果token和Redis中的token不一致，则验证失败
            if (!token.equals(redisToken)) {
                throw new CustomerAuthenticationException("token验证失败");
            }
            //如果存在token，则从token中解析出用户名
            String username = jwtUtils.getUsernameFromToken(token);

            //如果用户名为空，则解析失败
            if (ObjectUtils.isEmpty(username)) {
                throw new CustomerAuthenticationException("token解析失败");
            }
            //获取用户信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            //判断用户信息是否为空
            if (userDetails == null) {
                throw new CustomerAuthenticationException("token验证失败");
            }
            //创建身份验证对象
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //设置到Spring Security上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request, response, e);
        }
        filterChain.doFilter(request, response);
    }
}
